﻿using System.Web.Configuration;
using BLWCMS.Core.Weixin.Api;
using Nancy;
using Nancy.ModelBinding;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.Entities.Request;

namespace BLWCMS.Web.Modules
{
    public class WeixinModule : NancyModule
    {
        public WeixinModule()
        {
            Get["/api/weixin"] = p =>
            {
                PostModel postModel = this.Bind<PostModel>();
                string echostr = Request.Query["echostr"];
                if (CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, WeixinContext.WeixinToken))
                {
                    return echostr; //返回随机字符串则表示验证通过
                }
                else
                {
                    return "failed:" + postModel.Signature + "," +
                           CheckSignature.GetSignature(postModel.Timestamp, postModel.Nonce, WeixinContext.WeixinToken) +
                           "。如果你在浏览器中看到这句话，说明此地址可以被作为微信公众账号后台的Url，请注意保持Token一致。";
                }
            };


            Post["/api/weixin"] = p =>
            {
                string signature = Request.Query["signature"];
                string timestamp = Request.Query["timestamp"];
                string nonce = Request.Query["nonce"];
                string echostr = Request.Query["echostr"];

                if (!CheckSignature.Check(signature, timestamp, nonce, WeixinContext.WeixinToken))
                {
                    return "参数错误！";
                }

                //post method - 当有用户想公众账号发送消息时触发
                var postModel = new PostModel()
                {
                    Signature = signature,
                    Msg_Signature = Request.Query["msg_signature"],
                    Timestamp = timestamp,
                    Nonce = nonce,
                    //以下保密信息不会（不应该）在网络上传播，请注意
                    Token = WeixinContext.WeixinToken,
                    EncodingAESKey = WeixinContext.WeixinEncodingAesKey,
                    AppId = WeixinContext.WeixinAppId
                };

                //自定义MessageHandler，对微信请求的详细判断操作都在这里面。
                var messageHandler = new CustomMessageHandler(Request.Body, postModel);

                messageHandler.Execute();
                return messageHandler.ResponseDocument.ToString();
            };
        }
    }
}